package com.jrx.anytxn.investor.job.file.day.order.step;

import com.jrx.anytxn.investor.config.InvestorFileConfig;
import com.jrx.anytxn.investor.service.IInvestorFileService;
import com.jrx.anytxn.param.dto.investor.FileBean;
import com.jrx.anytxn.param.service.investor.IInvestorParamFileService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.batch.item.ItemWriter;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;


public class FileWriter implements ItemWriter<FileBean> {

    private IInvestorParamFileService fileService;

    private InvestorFileConfig fileConfig;

    private String fileType;

    public FileWriter(IInvestorParamFileService fileService,InvestorFileConfig fileConfig,String fileType){
        this.fileService = fileService;
        this.fileConfig = fileConfig;
        this.fileType = fileType;
    }



    @Override
    public void write(List<? extends FileBean> items) {
        if(CollectionUtils.isNotEmpty(items)){
            items.stream().collect(Collectors.groupingBy(FileBean::getInvestorId))
                    .forEach(
                            (investorId,list)->{
                                List<String> fileStringList = list.stream().map(FileBean::getFileString).collect(Collectors.toList());
                                try {
                                    fileService.generatingFile(fileStringList,fileConfig.getInvestorFilePath(),investorId,
                                            fileConfig.getInvestorFileName(), fileType);
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                    );

        }
    }
}
